package com.tianji.learning.until;

import lombok.Data;

import java.io.Serializable;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
@Data
public class DelayTask<T> implements Delayed, Serializable {
    // 延迟任务的纳秒值
    private Long deadlineNanos;
    // 延迟任务的数据
    private T data;

    public DelayTask(Duration delayTime, T data) {
        this.deadlineNanos = System.nanoTime() + delayTime.toNanos();
        this.data = data;
    }
    // 用于获取当前队列的任务，看还需要多久被执行
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(deadlineNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
    }
    // 对延迟队列中的任务进行排序
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return diff > 0 ? 1 : diff < 0 ? -1 : 0;


    }
}
